package com.kits.other


import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.btnGetFile).setOnClickListener {
            // 查表
            val uri = Uri.parse("content://com.kits.store.FileExProvider/file")
            val cursor = contentResolver.query(uri,null,null,null,null)

            if (cursor != null && cursor.count > 0){
                cursor.moveToFirst()
                do {
                    cursor?.takeIf {
                        it.count > 0
                    }?.let {
                        val uri = cursor.getString(cursor.getColumnIndex("URI"))
                        readFile(uri)
                        writeFile(uri)
                    }
                }while (cursor.moveToNext())
            }
        }
    }

    private fun readFile(uri:String){
        val fileUri = Uri.parse(uri)
        val inputStream = contentResolver.openInputStream(fileUri)
        inputStream?.let {
            val buf = ByteArray(inputStream.available())
            inputStream.read(buf)
            inputStream.close()
            println("获取的内容式：${String(buf)}")
        }

    }

    private fun writeFile(uri:String){
        val fileUri = Uri.parse(uri)
        val outputStream = contentResolver.openOutputStream(fileUri)
        outputStream?.let {
            outputStream.write("其他一个APP写入的，我就是测试一下啊\n".toByteArray())
            outputStream.close()
        }
    }

}